package org.jpass.dc.view.user;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.jpass.dc.business.user.bean.UserGroupVOBean;
import org.jpass.dc.business.user.bean.UserVOBean;
import org.jpass.dc.business.user.logic.UserGroupLogic;
import org.jpass.dc.business.user.logic.UserGroupLogicImpl;
import org.jpass.dc.business.user.logic.UserManageLogic;
import org.jpass.dc.business.user.logic.UserManageLogicImpl;
import org.jpass.dc.common.bean.Page;
import org.jpass.dc.common.email.SendEmail;
import org.jpass.dc.common.exception.ApplicationException;
import org.jpass.dc.common.util.Encrypter;
import org.jpass.dc.common.util.RefParaValue;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class UserManageAction extends ActionSupport {
	private static final long serialVersionUID = 1L;

	private Log log = LogFactory.getLog(getClass());
	
	private String userId;
	private String email;
	private String username;
	private String password;
	private String rePassword;
	private UserVOBean userVOBean = new UserVOBean();
	private UserGroupVOBean groupVOBean = new UserGroupVOBean();
	private UserManageLogic userManageLogic = new UserManageLogicImpl();
	private UserGroupLogic userGroupLogic = new UserGroupLogicImpl();

	/**用户登录**/
	public String login() throws Exception {
		ActionContext ctx = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
		try{
			if (!RefParaValue.empty(email) && !RefParaValue.empty(password)) {
				userVOBean.setEmail(email);
				userVOBean.setPassword(Encrypter.md5Encrypt(password));
				UserVOBean onlineUser = userManageLogic.login(userVOBean);
				if (!RefParaValue.empty(onlineUser)) {
					ctx.getSession().put("user", onlineUser); // 往session添加当前用户
					return Action.SUCCESS;
				} else {
					request.setAttribute("tip", "密码错误，请重新输入！");
					return Action.LOGIN;
				}
			} else {
				return Action.LOGIN;
			}
		}catch (ApplicationException e){  //抛出用户名不存在异常
			if("noUser".equals(e.getMessage())){
				request.setAttribute("tip", "用户名不存在，请输入正确的用户名！");
			}else if("noAct".equals(e.getMessage())){
				request.setAttribute("tip", "账户未激活，激活邮件已发送至您注册邮箱，请进行账户激活！");
			}
			return Action.LOGIN;
		}
	}

	/**用户注册**/
	public String register() throws Exception {
		ActionContext ctx = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
		String projectPath = request.getSession().getServletContext().getRealPath("/");
		String httpPathStr = request.getRequestURL().toString();
		int index = httpPathStr.indexOf("daycodefront/");
		String httpPath = httpPathStr.substring(0,index);
		try {
			String result="";
			List<UserGroupVOBean> listVar = userGroupLogic.findAllGroup();
			if(listVar.size()==0){
				this.addGroup();//新建用户组
			}
			List<UserGroupVOBean> list = userGroupLogic.findAllGroup();
			UserGroupVOBean group = null;
			if(!RefParaValue.empty(list)){
				for(int i=0;i<list.size();i++){
					UserGroupVOBean voBean = list.get(i);
					if("入门级程序员".equals(voBean.getGroupName())){
						group = list.get(i);
					}
				}
			}else{
				throw new ApplicationException("注册调用用户组发生错误！");
			}
			if(!RefParaValue.empty(group)){
				String workPath = "resource/" + username;
				File user_workpath = new File(projectPath + workPath);
				if(!user_workpath.isDirectory()){
					user_workpath.mkdir();
				}
				if(!RefParaValue.empty(username)){
					userVOBean.setEmail(email);
					userVOBean.setUsername(username);
					userVOBean.setPassword(Encrypter.md5Encrypt(password));
					userVOBean.setGroup(group);
					userVOBean.setWorkPath(workPath);
					userVOBean.setCreatedDate(new Date());
					userVOBean.setSendEmailTime(new Date());
					userVOBean.setPoint(0); //初始用户积分为0
					userVOBean.setIsMember(0); //是否为收费会员：0否；1是
					userVOBean.setIsActivated(0);//初始为未激活
					userVOBean.setLoginTimes(0); //登录次数
					userVOBean.setToken(Encrypter.md5Encrypt(username));
					result= userManageLogic.register(userVOBean);
				}
			}
			
			if("email".equals(result)){
				this.backRegisterInfo();  //返回注册表单信息
				request.setAttribute("tipEmail", "此邮箱已注册过，请更换邮箱！");
				return Action.ERROR;
			}else if("username".equals(result)){
				this.backRegisterInfo();   //返回注册表单信息
				request.setAttribute("tipUsername", "此用户名已存在，请更换用户名！");
				return Action.ERROR;
			}else if("success".equals(result)){
				request.setAttribute("tip", "恭喜，你已成功注册！");
				SendEmail se = new SendEmail();
				String sendEmailDate=new SimpleDateFormat("yyyy-MM-dd").format(new Date());
				String emailFlag = "register"; //用户注册标识
				se.sendEmail(emailFlag,httpPath,projectPath, username, email, sendEmailDate);//发送激活邮件
				return Action.SUCCESS;
			}else if(RefParaValue.empty(result)){
				return Action.ERROR;
			}else{
				request.setAttribute("tip", "注册时发生错误，请联系管理员！");
				return Action.ERROR;
			}
		} catch (ApplicationException e) {
			request.setAttribute("tip", e.getMessage());
			return Action.ERROR;
		}
	}

	/**邮件激活**/
	public String activate() throws Exception{
		ActionContext ctx = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
		String token = request.getParameter("token");
		String username = request.getParameter("username");
		
		try{
			if(!RefParaValue.empty(username)&&!RefParaValue.empty(token)){
				boolean result = userManageLogic.activate(username, token);
				if(result){
					return Action.SUCCESS; //激活成功
				}
			}
		}catch(ApplicationException e){
			request.setAttribute("tip", e.getMessage());
			return Action.ERROR;
		}
		return Action.ERROR;
	} 

	/**用户忘记密码**/
	public String forgetPass() throws Exception{
		ActionContext ctx = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
		String rootPath = request.getSession().getServletContext().getRealPath("/");
		String httpPathStr = request.getRequestURL().toString();
		int index = httpPathStr.indexOf("daycodefront/");
		String httpPath = httpPathStr.substring(0,index);
		try {
			UserVOBean user = userManageLogic.forgetPass(email);
			if(!RefParaValue.empty(user)){
				SendEmail se = new SendEmail();
				String sendEmailDate=new SimpleDateFormat("yyyy-MM-dd").format(new Date());
				String emailFlag = "forgetPass"; //忘记密码标识
				se.sendEmail(emailFlag,httpPath, rootPath, user.getUsername(), email, sendEmailDate);//发送忘记密码邮件
				request.setAttribute("email", email);
				return Action.SUCCESS;
			}else{
				request.setAttribute("tip", "不存在此注册邮箱！");
				return Action.ERROR;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Action.ERROR;
	}
	
	/**用户修改密码**/
	public String updatePass() throws Exception{
		ActionContext ctx = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
		String token = request.getParameter("token");
		String usernameVar = request.getParameter("username");
		try{
			if(!RefParaValue.empty(usernameVar)){
				if(!RefParaValue.empty(token)){
					userManageLogic.updatePass(username, null);
					request.setAttribute("username", usernameVar);
					return "updatePass";
				}else{
					UserVOBean user = userManageLogic.updatePass(username, password);
					if(!RefParaValue.empty(user)){
						return Action.SUCCESS;
					}
				}
			}else{
				return "updatePass";
			}
		}catch(ApplicationException e){
		request.setAttribute("tip", e.getMessage());
		return Action.ERROR;
	}
		return null;
	}
	
	/**后台分页返回用户列表**/
	public String userManage() throws Exception{
		ActionContext ctx = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
		String pageStr = request.getParameter("page");
		String findPara = request.getParameter("findPara");
		int pageIndex = 1;
		if(!RefParaValue.empty(pageStr)){
			pageIndex = Integer.parseInt(pageStr);
		}
		if(RefParaValue.empty(findPara)){
			findPara = "";
		}
		Page page = new Page(pageIndex,29); //每页显示29条记录（刚好）
		List<?> list = null;
		list =  userManageLogic.findUserList(page,findPara);
		request.setAttribute("page", page);
		request.setAttribute("list", list);
		return Action.SUCCESS;
	} 

	/**用户信息**/
	public String userInfo() throws Exception{
		ActionContext ctx = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
		String userId = request.getParameter("userId");
		try{
			UserVOBean user = userManageLogic.findUserInfoById(userId);
			String createdDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:dd").format(user.getCreatedDate());
			request.setAttribute("createdDate", createdDate);
			request.setAttribute("user", user);
		}catch(ApplicationException e){
			request.setAttribute("tip", e.getMessage());
			return Action.ERROR;
		}
		return Action.SUCCESS;
	} 
	
	/**修改用户信息**/
	public String updateUserInfo() throws Exception{
		List<UserGroupVOBean> list = userGroupLogic.findAllGroup();
		for(int i=0;i<list.size();i++){
			UserGroupVOBean group = list.get(i);
			if(group.getPointBegin()<=userVOBean.getPoint() 
					&& userVOBean.getPoint()<group.getPointEnd()){
				userVOBean.setGroup(group);
			}
		}
		try{
			if(userManageLogic.updateUserInfo(userVOBean)){
				this.writeReturnMsg("{'success':true}");
			};
		}catch(ApplicationException e){
			this.writeReturnMsg("{'success':false, 'msg':'" + e.getMessage() + "' , 'type':'error'}");
		}
		return null;
	}
	
	public String modifyUserInfo() throws Exception {
		try{
			if (userManageLogic.modifyUserInfo(userVOBean)) {
				ActionContext ctx = ActionContext.getContext();
				HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
				UserVOBean user = (UserVOBean) request.getSession().getAttribute("user");
				if("0".equals(userVOBean.getSex())) {
					user.setSex("女");
				} else  {
					user.setSex("男");
				}
				user.setBirthday(userVOBean.getBirthday());
				user.setNotes(userVOBean.getNotes());
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("success", true);
				map.put("msg", "Modify successfully.");
				map.put("user", user);
				Gson gson= new GsonBuilder().create();
				this.writeReturnMsg(gson.toJson(map));
			} else {
				this.writeReturnMsg("{'success':false, 'msg':'User is not exist.' , 'type':'error'}");
			}
		}catch(ApplicationException e){
			this.writeReturnMsg("{'success':false, 'msg':'" + e.getMessage() + "' , 'type':'error'}");
		}
		return null;
	}
	
	/**后台新建用户**/
	public String addUser() throws Exception{
		ActionContext ctx = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
		String rootPath = request.getSession().getServletContext().getRealPath("/");
		String groupStr = request.getParameter("groupValue");
		//String sexStr = request.getParameter("sex");
		List<UserGroupVOBean> list = userGroupLogic.findAllGroup();
		UserGroupVOBean group = null;
		if("1".equals(groupStr)){
			if(!RefParaValue.empty(list)){
				for(int i=0;i<list.size();i++){
					UserGroupVOBean voBean = list.get(i);
					if("入门级程序员".equals(voBean.getGroupName())){
						group = list.get(i);
					}
				}
			}
		}else if("2".equals(groupStr)){
			if(!RefParaValue.empty(list)){
				for(int i=0;i<list.size();i++){
					UserGroupVOBean voBean = list.get(i);
					if("中级程序员".equals(voBean.getGroupName())){
						group = list.get(i);
					}
				}
			}
		}else if("3".equals(groupStr)){
			if(!RefParaValue.empty(list)){
				for(int i=0;i<list.size();i++){
					UserGroupVOBean voBean = list.get(i);
					if("高级程序员".equals(voBean.getGroupName())){
						group = list.get(i);
					}
				}
			}
		}
		
		try{
			userVOBean.setGroup(group);
			String workPath = "resource/" + userVOBean.getUsername();
			File user_workpath = new File(rootPath + workPath);
			if(!user_workpath.isDirectory()){
				user_workpath.mkdir();
			}
			userVOBean.setPassword(Encrypter.md5Encrypt(userVOBean.getPassword()));
			userVOBean.setGroup(group);
			userVOBean.setWorkPath(workPath);
			userVOBean.setCreatedDate(new Date());
			userVOBean.setPoint(0);
			userVOBean.setLoginTimes(0);
			userVOBean.setIsMember(0); //是否为收费会员：0否；1是
			userVOBean.setIsOnline(0);
			//userVOBean.setSex("男");
			/*if("1".equals(sexStr)){
				userVOBean.setSex("男");
			}else{
				userVOBean.setSex("女");
			}*/
			String result = userManageLogic.register(userVOBean);
			if("email".equals(result)){
				this.writeReturnMsg("{'success':false, 'msg':'email' , 'type':'error'}");
			}else if("username".equals(result)){
				this.writeReturnMsg("{'success':false, 'msg':'username' , 'type':'error'}");
			}else if("success".equals(result)){
				this.writeReturnMsg("{'success':true}");
			}
		}catch(ApplicationException e){
			this.writeReturnMsg("{'success':false, 'msg':'" + e.getMessage() + "' , 'type':'error'}");
		}
		return null;
	} 
	
	/**返回重置用户密码**/
	public String resetPassForm() throws Exception{
		ActionContext ctx = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
		String userId = request.getParameter("userId");
		try{
			UserVOBean user = userManageLogic.findUserInfoById(userId);
			if(!RefParaValue.empty(user)){
				request.setAttribute("user", user);
			};
		}catch(ApplicationException e){
			request.setAttribute("tip", e.getMessage());
			return Action.ERROR;
		}
		return Action.SUCCESS;
	} 
	
	/**重置用户密码**/
	public String resetPass(){
		try{
			if(userManageLogic.resetPass(userId,password)){
				this.writeReturnMsg("{'success':true}");
			}
		}catch(Exception e){
			this.writeReturnMsg("{'success':false, 'msg':'" + e.getMessage() + "' , 'type':'error'}");
		}
		return null;
	} 
	
	/**删除用户**/
	public String deleteUser() throws Exception{
		ActionContext ctx = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
		String deleteIds = request.getParameter("deleteIds");
		try{
			userManageLogic.deleteUser(deleteIds);
			this.userManage();
		}catch(ApplicationException e){
			request.setAttribute("tip", e.getMessage());
			return Action.ERROR;
		}
		return Action.SUCCESS;
	} 
	
	/**验证登录信息**/
	public void validateLogin(){
		ActionContext ctx = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
		String validateImage = request.getParameter("validate");
		if(!RefParaValue.empty(validateImage)){
			String validateImageVar = validateImage.toLowerCase();
			String randVar = String.valueOf(ctx.getSession().get("rand")).toLowerCase();
			if(!validateImageVar.equals(randVar)){
				this.backRegisterInfo();
				this.addFieldError("tipValidate", "验证码错误！");
			}
		}
	}
	
	/**验证注册信息**/
	public void validateRegister(){
		ActionContext ctx = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
		String randVar = String.valueOf(ctx.getSession().get("rand")).toLowerCase();
		String validateImage = request.getParameter("validate");
		String validateImageVar="";
		if(!RefParaValue.empty(validateImage)){
			validateImageVar = validateImage.toLowerCase();
		}
		if("isReg".equals(request.getParameter("regFlag"))){
			if(!validateImageVar.equals(randVar)){
				this.backRegisterInfo();
				this.addFieldError("tipImage", "验证码错误！");
			}else{
				if(RefParaValue.empty(email)){
					this.addFieldError("email", "邮箱不能为空！");
				}else{
					Pattern p = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
					Matcher m = p.matcher(email);
					if(!m.find()){
						this.addFieldError("email", "请输入正确的电子邮箱！");
					}
				}
				if(RefParaValue.empty(username)){
					this.addFieldError("username", "用户名不能为空！");
				}else{
					Pattern p = Pattern.compile("\\w{4,20}$"); //由大小写字母、数字和下划线组成，长度为4到20
					Matcher m = p.matcher(username);
					if(!m.find()){
						this.addFieldError("username", "用户名由大小写字母、数字和下划线组成且长度为4到20！");
					}
				}
				if(RefParaValue.empty(password)){
					this.addFieldError("password", "设置密码不能为空！");
				}else{
					Pattern p = Pattern.compile("[a-zA-Z0-9]{6,18}$"); //由大小写字母、数字组成，长度为6到18
					Matcher m = p.matcher(password);
					if(!m.find()){
						this.addFieldError("password", "密码由大小写字母、数字组成且长度为6到18！");
					}
				}
				if(RefParaValue.empty(rePassword)){
					this.addFieldError("rePassword", "确认密码不能为空！");
				}
				if(!RefParaValue.empty(password) && !RefParaValue.empty(rePassword)
						&& !password.equals(rePassword)) {
					this.addFieldError("rePassword", "两次输入的密码不一样！");
				}
			}
		}
	}
	
	/**验证忘记密码请求信息**/
	public void validateForgetPass(){
		ActionContext ctx = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
		String validateImage = request.getParameter("validate");
		if(!RefParaValue.empty(validateImage)){
			String validateImageVar = validateImage.toLowerCase();
			String randVar = String.valueOf(ctx.getSession().get("rand")).toLowerCase();
			if(!validateImageVar.equals(randVar)){
				this.addFieldError("tipImage", "验证码错误！");
			}
		}
	}
	
	/**验证修改密码信息**/
	public void validateUpdatePass(){
		ActionContext ctx = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
		String validateImage = request.getParameter("validate");
		if(!RefParaValue.empty(validateImage)){
			String validateImageVar = validateImage.toLowerCase();
			String randVar = String.valueOf(ctx.getSession().get("rand")).toLowerCase();
			if(!validateImageVar.equals(randVar)){
				this.backRegisterInfo();
				this.addFieldError("tipValidate", "验证码错误！");
			}
		}
	}
	
	/**添加注册表单信息**/
	public void backRegisterInfo(){
		ActionContext ctx = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
		request.setAttribute("email", email);
		request.setAttribute("username", username);
		request.setAttribute("password", password);
		request.setAttribute("rePassword", rePassword);
	}
	
	/**添加用户组信息**/
	public String addGroup() throws Exception{
		UserGroupVOBean groupVOBean = new UserGroupVOBean();
		groupVOBean.setGroupName("入门级程序员");
		groupVOBean.setGroupLevel(0);
		groupVOBean.setPointBegin(0);
		groupVOBean.setPointEnd(50);
		groupVOBean.setNotes("");
		String groupId="";
		try {
			groupId = userGroupLogic.addGroup(groupVOBean);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return groupId; 
	}
	
	/** 用户注销  **/
	public String logout() {
		ActionContext ctx = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
		UserVOBean user = (UserVOBean) request.getSession().getAttribute("user");
		try {
			if(userManageLogic.updateLogoutStatus(user)) {
				request.getSession().removeAttribute("user");
				request.getSession().invalidate();
			} else {
				return Action.ERROR;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Action.SUCCESS;
	}
	
	private void writeReturnMsg(String msg) {
		ActionContext ctx = ActionContext.getContext();
		HttpServletResponse response = (HttpServletResponse) ctx.get(ServletActionContext.HTTP_RESPONSE);
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		try {
			PrintWriter out = response.getWriter();
			out.write(msg);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String getCurrentUserInfo() {
		ActionContext ctx = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
		UserVOBean user = (UserVOBean) request.getSession().getAttribute("user");
		//user.setGroup(null);
		//user.setPassword(null);
		//user.setSendEmailTime(null);
		//user.setSendForgetEmailTime(null);
		//user.setWorkPath(null);
		Map<String, UserVOBean> map = new HashMap<String, UserVOBean>();
		map.put("user", user);
		Gson gson= new GsonBuilder().create();
		try {
			String json = gson.toJson(map);
			ServletActionContext.getResponse().setCharacterEncoding("utf-8");
			ServletActionContext.getResponse().getWriter().print(json);
		} catch (IOException e) {
			e.printStackTrace();
			log.error("getCurrentUserInfo方法获取PrintWriter时发生错误，错误信息为：", e);
		}
		return null;
	}
	
	
	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getRePassword() {
		return rePassword;
	}

	public void setRePassword(String rePassword) {
		this.rePassword = rePassword;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	
	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public UserVOBean getUserVOBean() {
		return userVOBean;
	}

	public void setUserVOBean(UserVOBean userVOBean) {
		this.userVOBean = userVOBean;
	}

	public UserGroupVOBean getGroupVOBean() {
		return groupVOBean;
	}

	public void setGroupVOBean(UserGroupVOBean groupVOBean) {
		this.groupVOBean = groupVOBean;
	}

	public UserManageLogic getUserManageLogic() {
		return userManageLogic;
	}

	public void setUserManageLogic(UserManageLogic userManageLogic) {
		this.userManageLogic = userManageLogic;
	}

}
